import store from '@/store'
import { defineStore } from 'pinia'
import { getAccessToken, removeToken } from '@/utils/auth'
import { CACHE_KEY, useCache, deleteUserCache } from '@/hooks/useCache'
// import { getInfo, loginOut } from '@/api/login'
import { getUserInfo, userInfoRes } from '@/api/userInfo'
import {logout} from '@/api/login/index'

const { wsCache } = useCache()

interface UserInfoVO {
  // USER 缓存
  user: userInfoRes
}
const initData: UserInfoVO = {
  user: {
    id: 0,
    avatar: '',
    nickname: '',
    mobile: null,
    skills: '',
    remark: ''
  }
}

export const useUserStore = defineStore('admin-user', {
  // state: (): UserInfoVO => ({
    // permissions: wsCache.get(CACHE_KEY.PERMISSIONS) || initData.permissions,
    // roles: wsCache.get(CACHE_KEY.ROLES) || initData.roles,
    // isSetUser: wsCache.get(CACHE_KEY.IS_SET_USER) || initData.isSetUser,
    // user: wsCache.get(CACHE_KEY.USER) || initData.user,
    // company: wsCache.get(CACHE_KEY.COMPANY) || initData.company,
    // menus: wsCache.get(CACHE_KEY.ROLE_ROUTERS) || initData.menus
  // }),
  state: () => ({
    user: wsCache.get(CACHE_KEY.USER) || initData.user
  }),
  getters: {
    getUser(): userInfoRes {
      return this.user
    }
  },
  actions: {
    async setUserInfoAction() {
      const userInfo = await getUserInfo() as userInfoRes
      this.user = userInfo
      wsCache.set(CACHE_KEY.USER, userInfo)
    },
    async loginOut() {
      await logout()
      removeToken()
      deleteUserCache() // 删除用户缓存
    },
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
